// index.js
/**
 * 首页页面
 * @description 展示商品列表、搜索和分类功能的主页面
 */
const { goodsApi } = require('../../services/api')

Page({
  data: {
    goodsList: [], // 商品列表
    searchValue: '', // 搜索值
    currentPage: 1, // 当前页码
    pageSize: 10, // 每页数量
    loading: false, // 加载状态
    hasMore: true // 是否还有更多
  },

  onLoad: function() {
    this.loadGoodsList()
  },

  // 加载商品列表
  loadGoodsList: async function() {
    if (this.data.loading || !this.data.hasMore) return
    
    this.setData({ loading: true })
    try {
      const params = {
        page: this.data.currentPage,
        pageSize: this.data.pageSize,
        keyword: this.data.searchValue
      }
      const res = await goodsApi.getGoodsList(params)
      
      this.setData({
        goodsList: [...this.data.goodsList, ...res.data],
        loading: false,
        hasMore: res.data.length === this.data.pageSize,
        currentPage: this.data.currentPage + 1
      })
    } catch (err) {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  }
  
  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  // 搜索提交
  onSearchSubmit: function() {
    this.setData({
      goodsList: [],
      currentPage: 1,
      hasMore: true
    })
    this.loadGoodsList()
  }
})
